<template>
    <a-row>
        <a-row class='mytitle'>
            {{ $t('任务管理') }}
        </a-row>

        <a-row style="margin:1em">
            <a-card hoverable>
                <div style="display:flex;align-items: center;">
                    <div style="display: flex;align-items: center;">
                        <span>{{ $t('时间') }}：</span>
                        <a-range-picker show-time @change="onChange" :show-time="{ format: 'HH:mm' }"
                            format="YYYY-MM-DD HH:mm" valueFormat="YYYY-MM-DD HH:mm" @ok="handleTime" :ranges="dataRange">
                            <a-icon slot="suffixIcon" type="calendar" />
                        </a-range-picker>
                    </div>
                    <div style="display: flex;align-items: center;">
                        <span style="margin-left: 16px;">{{ $t('全部状态') }}:</span>
                        <a-select v-model="states" style="width: 246px;margin-left: 16px;" @change="handleState" mode="multiple" :default-value="['']">
                            <a-select-option value="" :disabled="stateDisabled">
                                全部
                            </a-select-option>
                            <a-select-option v-for="item in stateList" :value='item.value' :key="item.value">{{ item.label
                            }}</a-select-option>
                        </a-select>
                    </div>
                    <div style="display: flex;align-items: center;">
                        <span style="margin-left: 16px;">{{ $t('全部任务类型') }}:</span>
                        <a-select v-model="tag_ids" style="width: 396px;margin-left: 16px;" @change="handleTag" mode="multiple" :default-value="['']">
                            <!-- <a-select-option value="" :disabled="tagDisabled" key="0">
                                全部
                            </a-select-option> -->
                            <a-select-option v-for="item in tagList" :value='item.index' :key="item.index">{{ item.chinese
                            }}</a-select-option>
                        </a-select>
                    </div>
                    <a-button style="margin-left: 16px;" type='primary' @click="handleSearch">
                        <Iconfont class="icon button-icon-style" type="icon-search16f"></Iconfont>
                        {{ $t('查询') }}
                    </a-button>
                </div>

                <a-table style="margin-top: 16px;" class="bigstyle" :columns="columns" :loading="loading"
                    :dataSource="dataList" size="small" rowKey='task_id' :pagination='pagination'
                    :locale="defaultSetting" :scroll="{ x: 1340 }">
                    <template slot="task_name" slot-scope="task_name, record">
                        <template v-if="$store.state.language == 'zh'">
                            <span v-if="taskNameList[task_name]">{{ asFormat(taskNameList[task_name].zh_CN,record.params) }}</span>
                            <span v-else>-</span>
                        </template>
                        <template v-else>
                            <span v-if="taskNameList[task_name]">{{ asFormat(taskNameList[task_name].en_US,record.params) }}</span>
                            <span v-else>-</span>
                        </template>
                    </template>
                    <template slot="tag_id" slot-scope="tag_id, record">
                        <span v-if="$store.state.language == 'zh'">{{ tagList[tag_id - 1].chinese }}</span>
                        <span v-else>{{ tagList[tag_id - 1].english }}</span>
                    </template>
                    <template slot="duration" slot-scope="duration, record">
                        <span>{{ secondTransform(duration) }}</span>
                    </template>
                    <template slot="state" slot-scope="state, record">
                        <div v-if="state === 0">
                            <span class="dot"></span>
                            {{ $t('进行中') }}
                        </div>
                        <div v-else-if="record.flag == 0 && state === 1">
                            <span class="dot success"></span>
                            {{ $t('成功') }}
                        </div>
                        <div v-else-if="record.flag == 1 && state === 1">
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span v-if="taskNameList[record.params.des] && $store.state.language == 'zh'">{{
                                        asFormat(taskNameList[record.params.des].zh_CN,record.params) }}</span>
                                    <span
                                        v-else-if="taskNameList[record.params.des] && $store.state.language == 'en'">{{
                                            asFormat(taskNameList[record.params.des].en_US,record.params) }}</span>
                                    <span v-else>{{ record.params.des }}</span>
                                </template>
                                <span class="dot fail"></span>
                                <span style="margin-left: 4px;">{{ $t('失败') }}</span>
                                <Iconfont style="margin-left: 8px;" class="icon table-operation-icon"
                                    type="icon-view16f">
                                </Iconfont>
                            </a-tooltip>
                        </div>
                    </template>
                    <template slot="start_time" slot-scope="start_time, record">
                        <span v-if="start_time">{{ start_time.slice(0, 19) }}</span>
                        <span v-else>-</span>
                    </template>
                    <template slot="end_time" slot-scope="end_time, record">
                        <span v-if="end_time">{{ end_time.slice(0, 19) }}</span>
                        <span v-else>-</span>
                    </template>
                </a-table>


            </a-card>
        </a-row>

    </a-row>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import NoAuthPage from '@/components/common/NoAuthPage'
import moment from "moment";

let dataRange = {
    '今天': [moment().startOf("day"), moment()],
    '昨天': [
        moment().startOf("day").subtract(1, "days"),
        moment().startOf("day").subtract(0, "days"),
    ],
    '最近一周': [moment().startOf("day").subtract(1, "weeks"), moment()],
    '最近1个月': [moment().startOf("day").subtract(1, "months"), moment()],
    '最近3个月': [moment().startOf("day").subtract(3, "months"), moment()],
    '最近半年': [moment().startOf("day").subtract(6, "months"), moment()],
    '最近1年': [moment().startOf("day").subtract(1, "years"), moment()],
}

export default {
    components: { EmptyData, NoAuthPage },
    data() {
        return {
            columns: [
                { title: this.$t('任务名称'), dataIndex: 'task_name', key: 'task_name', width: 200, fixed: 'left', scopedSlots: { customRender: 'task_name' } },
                { title: this.$t('任务类型'), dataIndex: 'tag_id', key: 'tag_id', scopedSlots: { customRender: 'tag_id' } },
                { title: this.$t('发生节点'), dataIndex: 'hostname' },
                { title: this.$t('持续时间'), dataIndex: 'duration', key: 'duration', scopedSlots: { customRender: 'duration' } },
                { title: this.$t('任务状态'), dataIndex: 'state', key: 'state', scopedSlots: { customRender: 'state' } },
                { title: this.$t('操作人'), dataIndex: 'username', key: 'username' },
                { title: this.$t('开始时间'), dataIndex: 'start_time', key: 'start_time', scopedSlots: { customRender: 'start_time' } },
                { title: this.$t('结束时间'), dataIndex: 'end_time', key: 'end_time', scopedSlots: { customRender: 'end_time' } },
            ],
            pagination: {
                defaultPageSize: 10,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '15', '20'],
                onShowSizeChange: (current, pageSize) => { this.pageSize = pageSize; },
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`,
            },
            dataList: [],
            copyList: [],
            tagList: [],
            stateList: [
                { label: '成功', value: 1 },
                { label: '失败', value: 2 },
                { label: '进行中', value: 3 },
            ],
            loading: false,
            tag_ids: [],
            states: [''],
            start_time: '',
            end_time: '',
            defaultSetting: { emptyText: <EmptyData /> },
            dataRange,
            stateDisabled: false,
            tagDisabled: false,
        }
    },
    computed: {
        taskNameList() {
            return this.$store.state.basetips
        },
        language() {
            return this.$store.state.language
        }
    },
    watch: {
        language(value) {
            this.columns = [
                { title: this.$t('任务名称'), dataIndex: 'task_name', key: 'task_name', width: 200, fixed: 'left', scopedSlots: { customRender: 'task_name' } },
                { title: this.$t('任务类型'), dataIndex: 'tag_id', key: 'tag_id', scopedSlots: { customRender: 'tag_id' } },
                { title: this.$t('发生节点'), dataIndex: 'hostname' },
                { title: this.$t('持续时间'), dataIndex: 'duration', key: 'duration', scopedSlots: { customRender: 'duration' } },
                { title: this.$t('任务状态'), dataIndex: 'state', key: 'state', scopedSlots: { customRender: 'state' } },
                { title: this.$t('操作人'), dataIndex: 'username', key: 'username' },
                { title: this.$t('开始时间'), dataIndex: 'start_time', key: 'start_time', scopedSlots: { customRender: 'start_time' } },
                { title: this.$t('结束时间'), dataIndex: 'end_time', key: 'end_time', scopedSlots: { customRender: 'end_time' } },
            ]
        }
    },
    async mounted() {
        await this.getTag()
        await this.getList()
    },
    methods: {
        async getTag() {
            this.loading = true
            const { data } = await this.$api.task.getTaskTagApi()
            const list = []
            for (const key in data) {
                const element = data[key];
                const item = { chinese: element.chinese, english: element.english, index: key }
                list.push(item)
            }
            this.tagList = list
            this.loading = false
        },
        async getList(params) {
            this.loading = true
            const { data } = await this.$api.task.getAllTaskApi(params)
            this.dataList = data
            this.copyList = data
            this.loading = false
        },
        secondTransform(second) {
            let d = moment.duration(second, 'seconds');
            let result = Math.floor(d.asDays()) + '天' + d.hours() + '时' + d.minutes() + '分' + d.seconds() + '秒'
            return result
        },
        onChange(date, dateString) {
            if (date[0] !== undefined && date[1] !== undefined) {
                this.start_time = date[0] + ':00'
                this.end_time = date[1] + ':00'
            } else {
                this.start_time = ''
                this.end_time = ''
            }
        },
        handleTime() {
            this.getList({
                start_time: this.start_time,
                end_time: this.end_time,
                states: this.states[0] == '' ? [] : this.states,
                tag_ids: this.tag_ids,
            })
        },
        handleSearch() {
            this.getList({
                start_time: this.start_time,
                end_time: this.end_time,
                states: this.states[0] == '' ? [] : this.states,
                tag_ids: this.tag_ids,
            })
        },
        handleState(value) {
            const list = this.stateList.map(item => item.value)
            const flag = list.every((item) => value.includes(item))
            // 状态全勾上
            if (flag) {
                this.stateDisabled = true
                this.states = list
            // 状态没有全部勾上
            } else {
                this.stateDisabled = false
                this.states = this.states.filter(item => item !== '')
            }
            // 勾上全部
            if (value.slice(-1)[0] == '') {
                this.states = ['']
            }
            if (value.length == 0) {
                this.states = ['']
            }
            this.getList({
                start_time: this.start_time,
                end_time: this.end_time,
                states: this.states[0] == '' ? [] : this.states,
                tag_ids: this.tag_ids,
            })
        },
        handleTag(value) {
            // const list = this.tagList.map(item => item.index)
            // const flag = list.every((item) => value.includes(item))
            // // 状态全勾上
            // if (flag) {
            //     this.tagDisabled = true
            //     this.tag_ids = list
            // // 状态没有全部勾上
            // } else {
            //     this.tagDisabled = false
            //     this.tag_ids = this.tag_ids.filter(item => item !== '')
            // }
            // // 勾上全部
            // if (value.slice(-1)[0] == '') {
            //     this.tag_ids = ['']
            // }
            this.getList({
                start_time: this.start_time,
                end_time: this.end_time,
                states: this.states[0] == '' ? [] : this.states,
                tag_ids: this.tag_ids,
            })
        },
        handleType(value) {
            this.loading = true
            if (value == '全部') {
                this.dataList = this.copyList
            } else {
                const index = this.tagList.findIndex(item => item.chinese == value)
                const list = this.copyList.filter(item => item.tag_id == index)
                this.dataList = list
            }
            this.loading = false
        }
    }
}
</script>

<style lang="scss" scoped>
.success {
    background-color: #129a9a;
}

.fail {
    background-color: #b62832
}
</style>
